import {specslist,specscount} from '../../../request/api'

// 封装一个接口类型
interface Stataspecs{
    userList:Array<object>
}

const state = {
    specsList:[],
    page:1,//页码
    size:2, // 页码初始值
    count:0 // 总数量
}

const getters = {
    getSpecs(state:any){
        return state.specsList
    },
    // 返回总数
    getCount(state:any){
        return state.count
    },
    // 返回当前显示条数
    getSize(state:any){
        return state.size
    }
}

const mutations = {
    SPECSLIST(state:any,payload:any){
        state.specsList = payload
    },
    SPECSCOUNT(state:any,payload:any){
        state.count = payload
    },
    CHANGEPAGE(state:any,payload:any){
        state.page = payload
    }
}

const actions = {
    // 封装一个获取列表行动
    getSpecsActions(context : any){
        // 调用接口
        specslist({
            size:context.state.size,//查询条数
            page: context.state.page//页码
        }).then((res) => {
            console.log(res);
            context.commit('SPECSLIST',res.list)
            let list: any = res.list ? res.list : []
            if(context.state.page !=1 && list.length == 0){
                context.dispatch('changePageActions',context.state.page -1)
            }
        })
    },
    // 封装一个获取总数的行动
    async getCountActions({commit}:any){
        let res : any = await specscount();
        commit('SPECSCOUNT',res.list[0].total)
    },
    // 封装一个切换页码行动
    changePageActions(context:any,payload:any){
        // 当用户切换页码 我们需要修改page
        context.commit('CHANGEPAGE',payload)
        // 重新调用列表
        context.dispatch('getSpecsActions')
    }
}   

export default { 
    state,
    getters,
    mutations,
    actions,
    namespaced:true
}